package com.woniu.service.impl;

import com.woniu.entity.Department;
import com.woniu.mapper.DepartmentMapper;
import com.woniu.mapper.EmployeeMapper;
import com.woniu.service.DepartmentService;
import com.woniu.util.ResponseEnum;
import com.woniu.util.ResponseUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class DepartmentServiceImpl implements DepartmentService {

    @Resource
    private DepartmentMapper departmentMapper;

    @Resource
    private EmployeeMapper employeeMapper;

    /**
     * 添加部门，需要检查部门名是否已存在
     */
    @Override
    public ResponseUtil add(Department department) {
        Department existingDept = departmentMapper.findByName(department.getName());
        if (existingDept != null) {
            // 如果部门已存在，则添加失败
            return ResponseUtil.get(ResponseEnum.FAIL, "部门已存在,请更换");
        }
        int result = departmentMapper.add(department);
        return result > 0 ? ResponseUtil.get(ResponseEnum.OK) : ResponseUtil.get(ResponseEnum.FAIL);
    }

    /**
     * 更新部门，可以更新名称或状态
     * 如果是更新名称，需要检查新名称是否被其他部门占用
     */
    @Override
    public ResponseUtil update(Department department) {
        // 检查新名称是否已被其他部门使用
        Department existingDept = departmentMapper.findByName(department.getName());
        if (existingDept != null && !existingDept.getDeptId().equals(department.getDeptId())) {
            // 如果找到了同名部门，且不是当前正在修改的这个部门，则说明名称冲突
            return ResponseUtil.get(ResponseEnum.FAIL, "部门名称已存在,请更换");
        }
        int result = departmentMapper.update(department);
        return result > 0 ? ResponseUtil.get(ResponseEnum.OK) : ResponseUtil.get(ResponseEnum.FAIL);
    }

    /**
     * 删除部门，需要检查该部门下是否还有员工
     */
    @Override
    public ResponseUtil delete(Integer deptId) {
        // 使用我们刚刚添加的新方法检查员工数量
        int employeeCount = employeeMapper.countByDeptId(deptId);
        if (employeeCount > 0) {
            // 如果部门下还有员工，则删除失败
            return ResponseUtil.get(ResponseEnum.FAIL, "部门存在员工,不能直接删除");
        }
        int result = departmentMapper.delete(deptId);
        return result > 0 ? ResponseUtil.get(ResponseEnum.OK) : ResponseUtil.get(ResponseEnum.FAIL);
    }

    @Override
    public ResponseUtil findAll() {
        List<Department> departmentList = departmentMapper.findAll();
        return !departmentList.isEmpty() ? ResponseUtil.get(ResponseEnum.OK, departmentList) : ResponseUtil.get(ResponseEnum.FAIL);
    }

    @Override
    public ResponseUtil findById(Integer deptId) {
        Department department = departmentMapper.findById(deptId);
        return department != null ? ResponseUtil.get(ResponseEnum.OK, department) : ResponseUtil.get(ResponseEnum.FAIL);
    }
}